package com.example.test.utils;

import cn.hutool.http.HttpRequest;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

@Slf4j
public class HttpUtil {

    /**
     * get请求
     * @param url
     * @param params
     * @return
     */
    public static String get(String url, Map<String,String> params){
        return get(url, params, null);
    }

    /**
     * get请求
     * @param url
     * @param params 参数
     * @param header 请求头
     * @return
     */
    public static String get(String url,Map<String,String> params,Map<String,String> header){
        if (params != null && params.size()>0){
            url = url + "?";
            for (Map.Entry<String,String> entry : params.entrySet()){
                url = url + entry.getKey() + "=" + entry.getValue() + "&";
            }
            url = url.substring(0, url.length() - 1);
        }
        HttpRequest httpRequest = HttpRequest.get(url);
        //设置请求头
        if (header != null && header.size()>0){
            for (String key : header.keySet()){
                httpRequest.header(key, header.get(key));
            }
        }
        log.info("url:"+url);
        String result =  httpRequest.execute().body();
        return result;
    }


    public static String postJson(String url, String json, Map<String,String> header){
        HttpRequest httpRequest = HttpRequest.post(url);
        //设置请求头
        if (header != null && header.size()>0){
            for (String key : header.keySet()){
                httpRequest.header(key, header.get(key));
            }
        }
        httpRequest.body(json);
        log.info("url:"+url);
        log.info("json:"+json);
        String result = httpRequest.execute().body();
        return result;
    }

    /**
     * form表单提交
     * @param url
     * @param formData
     * @param header
     * @return
     */
    public static String postForm(String url, Map<String,Object> formData, Map<String,String> header){
        HttpRequest httpRequest = HttpRequest.post(url);
        //设置请求头
        if (header != null && header.size()>0){
            for (String key : header.keySet()){
                httpRequest.header(key, header.get(key));
            }
        }
        //设置表单数据
        if (formData != null && formData.size()>0){
            for (String key : formData.keySet()){
                httpRequest.form(key, formData.get(key));
            }
        }
        log.info("url:"+url);
        log.info("params:"+formData.toString());
        String result = httpRequest.execute().body();
        return result;
    }
}
